package main

import (
	"fmt"
	"os"
)

const filename = "../maze.in"

func ReadMazeSource(filename string) [][]int {
	file, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	var row, col int
	_, err = fmt.Fscanf(file, "%d %d", &row, &col) //这里不能用bufio.Reader(file),数据错误
	if err != nil {
		panic(err)
	}

	maze := make([][]int, row)
	for i := range maze {
		maze[i] = make([]int, col)
		for j := range maze[i] {
			fmt.Fscanf(file, "%d", &maze[i][j])
		}
	}
	return maze
}

type Point struct {
	i, j int
}

var dirs = [4]Point{
	{-1, 0}, {1, 0}, {0, -1}, {0, 1}}

// 获取下一步点坐标
func (p *Point) nextStepPoint(n Point) Point {
	return Point{p.i + n.i, p.j + n.j}
}

// 获取点的所在数据
func (p *Point) at(grid [][]int) int {
	return grid[p.j][p.i]
}

func work(maze [][]int, start, end Point) [][]int {
	steps := make([][]int, len(maze))
	for index := range steps {
		steps[index] = make([]int, len(maze[index]))
	}
	currentPoints := []Point{start}

	for {

		if len(currentPoints) == 0 {
			break
		}
		current := currentPoints[0]
		for _, n := range dirs {
			next := current.nextStepPoint(n)
			if next.i < 0 || next.i >= len(maze[1]) { //x坐标越界
				continue
			}
			if next.j < 0 || next.j >= len(maze) { //y坐标越界
				continue
			}
			nextVal := next.at(maze) //下个点的数据
			currentStep := current.at(steps)
			nextstep := currentStep + 1

			if nextVal == 1 { //障碍
				continue
			}

			if next.at(steps) != 0 || (next.i == 00 && next.j == 0) { //返回上一步
				continue
			}

			steps[next.j][next.i] = nextstep
			currentPoints = append(currentPoints, next)
		}
		currentPoints = currentPoints[1:]
	}

	return steps
}

func main() {

	maze := ReadMazeSource(filename)
	for _, v := range maze {
		fmt.Println(v)
	}
	fmt.Println("----------------------")
	result := work(maze, Point{0, 0}, Point{4, 5})
	for _, v := range result {
		fmt.Println(v)
	}

}
